package com.example.interceptor;

import com.example.Util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        // 排除不需要拦截的路径
        if (isExcludedPath(requestURI)) {
            return true;
        }

        String token = request.getHeader("Authorization");
        if (token != null && jwtUtils.validateToken(token)) {
            if (jwtUtils.validateToken(token)) {
                return true;
            }
        }

        response.setStatus(401);
        response.getWriter().write("{\"code\":401,\"msg\":\"Invalid token\"}");
        return false;
    }

    private boolean isExcludedPath(String uri) {
        // 登录接口直接放行
        if ("/auth/login".equals(uri)) {
            return true;
        }

        // Knife4j 相关路径放行
        return uri.startsWith("/doc.html") ||
                uri.startsWith("/webjars/") ||
                uri.startsWith("/swagger-resources") ||
                uri.startsWith("/v2/api-docs") ||
                uri.startsWith("/v3/api-docs");
    }
}